<?php
/**
 * @Author:      Zy
 * @DateTime:    2018-3-07 16:32:48
 * @Description: 用于 pms 商品管理
 */
class PMSProductController extends BaseController {
    
    /**
     *  第三级分类列表
     * */
    public function level_3(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $list = SupplyClassification :: where("level",3)->where("name","like",'%'.Input::get("key").'%'); 
            if(Input::get("parent_id") != "") $list->where("parent_id",Input::get("parent_id")); //如果存在pid

            $list = $list->skip(0)->take(50)->orderBy("id","ASC")->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["lists"=>$list]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "product/level_3", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
    2级分类列表
     * */
    public function level_2(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $list = SupplyClassification :: where("level",2)->where("name","like",'%'.Input::get("key").'%'); 
            if(Input::get("parent_id") != "") $list->where("parent_id",Input::get("parent_id")); //如果存在pid

            $list = $list->skip(0)->take(50)->orderBy("id","ASC")->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["lists"=>$list]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "product/level_2", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
    1级分类列表
     * */
    public function level_1(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',      
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $list = SupplyClassification::where("level",1)
                    ->where("name","like",'%'.Input::get("key").'%')
                    ->skip(0)->take(50)
                    ->orderBy("id","ASC")
                    ->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["lists"=>$list]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "product/level_1", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * 计量单位
     * */
    public function unitList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',   
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            $list = DataSupplyUnit::where("name","like",'%'.Input::get("key").'%')
                    ->skip(0)->take(50)
                    ->orderBy("id","ASC")
                    ->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["lists"=>$list]);
        }while(false);
            Log::info("info", array("system" => "pms" ,"event" => "product/unitList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:    2018-03-09 09:42:21
     * @Description: 获取车辆型号 根据车品牌 车系和年款 获取车型
     */
    public function models(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'brand' => 'required',
                'series' => 'required',
                'year' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            //传入参数
            // $token = Input::get('token');
            $brand = Input::get('brand');
            $series = Input::get('series');
            $year = urldecode(Input::get('year'));
            $key = Input::get('key');

            //获取品牌车辆的厂商
            $models = DataCarStandardInfo::where('brand_name_id',$brand)
                ->where('series_name_id',$series)
                ->where('model_year',$year)
                ->select(array('id','model_name as model','oil_viscosity'));
            if ($key != "") $models->where("model_name","like",'%'.$key.'%');
            $models = $models->distinct()
                ->skip(0)->take(50)
                ->get();

            $result = array('list' => $models);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/models", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zy
     * @DateTime:    2018-03-09 09:50:14
     * @Description: 获取 指定车品牌车系 的车型年款
     */
    public function years(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'brand' => 'required',
                'series' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            //传入参数
            // $token = Input::get('token');
            $brand = Input::get('brand');
            $series = Input::get('series');
            $key = Input::get('key');

            //获取品牌车辆的厂商
            $years = DataCarStandardInfo::where('brand_name_id',$brand);
            if ($key != "") $years->where("model_year","like",'%'.$key.'%');
            $years = $years->where('series_name_id',$series)
                ->select(array('model_year as year'))
                ->distinct()
                ->skip(0)->take(50)
                ->get();
            $result = array('list' => $years);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/years", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zy
     * @DateTime:    2018-03-09 09:53:13
     * @Description: 获取指定品牌的车系
     */
    public function series(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'brand' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }

            //传入参数
            // $token = Input::get('token');
            $key = Input::get('key');
            $brand = Input::get('brand');
            
            //获取品牌车辆的厂商
            $factories = DataCarStandardInfo::where('brand_name_id',$brand);
            if ($key != "") $factories->where('series_name','like','%'.$key.'%');
            $factories = $factories->select(array('series_name_id','series_name'))
                ->distinct()
                ->skip(0)->take(50)
                ->get();
            
            $result = array('list' => $factories);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/series", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zy
     * @DateTime:    2018-03-09 10:06:45
     * @Description: 获取的车品牌
     */
    public function brands(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $key = Input::get('key');
            
            //获取车辆品牌信息
            $brands = DataCarBrand::select(array('id','initial','name','icon'));
            if ($key != "") $brands->where('name','like','%'.$key.'%');
            $brands = $brands->skip(0)->take(50)->get();
            $result = array('list' => $brands);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/brands", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:    2018-03-8 15:06:45
     * @Description: 搜索耗材
     */
    public function search(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            //根据1,2,3级分类。查找三级分类. 验证是否有三级分类，没有第三级分类，直接返回空
            $level_3 = Input::get('level_3'); 
            $level_2 = Input::get('level_2');
            $level_1 = Input::get('level_1');
            if ($level_3 != "" || $level_2 != "" || $level_1 != "") {
                $level_arr = [0]; //如果结果是空的，whereIN 中不能是空的
                $level = SupplyClassification::select("supply_classification.*")
                        ->leftJoin("supply_classification as lev2","supply_classification.parent_id","=","lev2.id")
                        ->leftJoin("supply_classification as lev1", "lev2.parent_id","=","lev1.id");
                if($level_3 != "") {
                    $level->where("supply_classification.level",3);
                    $level->where("supply_classification.id",$level_3);
                }
                if($level_2 != "") {
                    $level->where("lev2.level",2);
                    $level->where("lev2.id",$level_2);
                }
                if($level_1 != "") {
                    $level->where("lev1.level",1);
                    $level->where("lev1.id",$level_1);
                }


                $level = $level->orderBy("supply_classification.id")->get();

                if (!empty($level)) {
                    foreach ($level as $v) {
                        $level_arr[] =  $v->id;
                    }
                }
            }
            
            //验证车型是否有对应的耗材,车型没有对应的耗材，直接返回空
            $model_id = Input::get('model_id');
            if ($model_id != "") {
                $dpi_arr = [0];
                $dpi = DataSupplyProductItem::select("supply_item_id")->where("car_model_id",$model_id)->where("status",1)->groupBy("supply_item_id")->get();
                if (!empty($dpi)) {
                    foreach ($dpi as $v) {
                        $dpi_arr[] = $v['supply_item_id'];
                    }
                }

            }

            //开始耗材查询
            $status = Input::get('status');
            $type = Input::get('type');
            $volume_size = Input::get('volume_size'); //计量数量
            $unit_id = Input::get('unit_id');//计量单位id
            $brand_name = Input::get('brand_name');//耗材品牌
            $series_name = Input::get('series_name');//耗材系列
            $code = Input::get('code');//耗材编码
            $sale_unit_id = Input::get('sale_unit_id');//商品单位id
            $retrieval_code = Input::get('retrieval_code');//商品信息
            
            $search_arr = ["id","brand_id","brand_name","series_id","series_name","model","status","type","unit_id","sale_unit_id","volume_size","code","name","supply_classification_id","commodity_code","retrieval_code","car_model_comments"];
            $list = SupplyItem::select($search_arr);
            if ($retrieval_code != "") $list->where("retrieval_code","like",'%'.$retrieval_code.'%');
            if ($status != "") $list->where("status",$status);
            if ($type != "") $list->where("type",$type);
            if ($volume_size != "") $list->where("volume_size","like",'%'.$volume_size.'%');
            if ($unit_id != "") $list->where("unit_id",$unit_id);
            if ($brand_name != "") $list->where("retrieval_code","like",'%'.$brand_name.'%');
            if ($series_name != "") $list->where("retrieval_code","like",'%'.$series_name.'%');
            if ($code != "") $list->where("retrieval_code","like",'%'.$code.'%');
            if ($sale_unit_id != "") $list->where("sale_unit_id",$sale_unit_id);
            if ($model_id != "") $list->whereIn("id",$dpi_arr); //如果有此条件，$dpi_arr就会被赋值，赋值后是空的，就搜不到了
            if ($level_3 != "" || $level_2 != "" || $level_1 != "") $list->whereIn("supply_classification_id",$level_arr); //如果有此条件，并且前面的判断没有中断，说明$level_arr有值

            $count = $list->count();
            $page_size = Input::get("page_size",20);
            $page = Input::get("page",1);
            $list = $list->skip($page_size*($page-1))->take($page_size)->orderBy("id","ASC")->get();
            foreach ($list as $v) {
                $level_3_info = SupplyClassification::select("name")->where("id",$v->supply_classification_id)->first();
                $v->level_3_name = $level_3_info->name;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ['count'=>$count,"list"=>$list]);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/search", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:    2018-03-09 10:06:45
     * @Description: 商品详情-明细
     */
    public function info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $id = Input::get('id'); //SKUid
            
            //获取SKU信息
            $info = SupplyItem::where("id",$id)->first();
            $level_3_info = SupplyClassification::find($info->supply_classification_id);
            $info->level_3_name = $level_3_info->name;
            $level_2_info = SupplyClassification::find($level_3_info->parent_id);
            $info->level_2_name = $level_2_info->name;
            $level_1_info = SupplyClassification::find($level_2_info->parent_id);
            $info->level_1_name = $level_1_info->name;
            $unit = DataSupplyUnit::find($info->unit_id);
            $info->unit_name  = $unit->name;
            $sale_unit = DataSupplyUnit::find($info->sale_unit_id);
            $info->sale_unit_name  = $sale_unit->name;
            $info->picture = DataSupplyItemIcon::where("supply_item_id",$info->id)->where("status",1)->orderBy("id","ASC")->get();
            $info->pms_supply_item_url = Config::get('config.pms_supply_item_url');
            $info -> transport = DB::table('anhui_data.supply_transport_signs_item as stsi')
                    ->leftJoin("anhui_data.supply_transport_signs as sts","stsi.supply_transport_signs_id","=","sts.id")
                    ->where('stsi.supply_item_id', $id)->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["info"=>$info]);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:    2018-03-09
     * @Description: 商品详情-库存
     */
    public function remain(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $id = Input::get('id'); //SKUid

            $list = MaintenanceStorageItem::select(DB::raw('id,data_id,shop_id,sum(current_number) as current_number'))
                    ->where("item_id",$id)
                    ->where("type",1)
                    ->where("status",1)
                    ->groupBy("shop_id")
                    ->groupBy("data_id")
                    ->get();
            $new_list = [];
            $count = ["all"=>0, "pei"=>0, "fu"=>0];
            if (!empty($list)) {
                foreach ($list as $v) {
                    $database = MainDateBase::find($v->data_id);
                    $v->name = $database->name;
                    $v->type = $database->type;

                    if (!isset($new_list[$v->shop_id]["datebase"])) { //如果第一次加载，辅料库，和配件库都需要位置
                        $new_list[$v->shop_id]["datebase"][0] = ["type"=>0,"current_number"=>""];
                        $new_list[$v->shop_id]["datebase"][1] = ["type"=>1,"current_number"=>""];  
                    }
                    
                    $new_list[$v->shop_id]["datebase"][$v->type] = $v;
                    
                    if (isset($new_list[$v->shop_id]["current_number"])) {
                        $new_list[$v->shop_id]["current_number"] += $v->current_number;
                    }else {
                        $new_list[$v->shop_id]["current_number"] = $v->current_number;
                    }
                    
                    if (!isset($new_list[$v->shop_id]["shop_name"])) {
                        $shop = MaintenanceShops::select("name")->find($v->shop_id);
                        $new_list[$v->shop_id]["shop_name"] = $shop->name;
                    }
                    
                    //计算所有的总数
                    $count['all'] += $v['current_number'];
                    if ($v['type'] == 0 )  $count["pei"] += $v['current_number'];
                    if ($v['type'] == 1 )  $count["fu"] += $v['current_number'];
                }

                foreach ($new_list as $k=>$v) { //聚合完成后。如果辅料库，和配件库都是0 就不显示了
                    if($v["current_number"] == 0){
                        unset($new_list[$k]);
                    }
                }
                
                $new_list = array_values($new_list);
            }
            //print_r($list);die;
            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>$new_list,"count"=>$count]);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:    2018-03-09 
     * @Description: 商品详情-比价
     */
    public function skuMoney(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            $id = Input::get('id'); //SKUid
            $purchase_status = Input::get('purchase_status'); //供应商状态
            $regular_pay = Input::get('regular_pay');//是否定期结算 1是 0否（现金结算）
            $sort = Input::get('sort'); //报价排序  1含升,  2含降,  3无升,  4 无降
            $price = SupplierGoodsPrice::select("supplier_goods_price.id","supplier_goods_price.tax_price","supplier_goods_price.no_tax_price","ms.id as suppler_id","ms.status","ms.purchase_status","ms.name","ms.regular_pay")
                    ->leftJoin("maintenance_supplier as ms","supplier_goods_price.supplier_id","=","ms.id")
                    ->where("goods_id",$id)
                    ->where("supplier_goods_price.status",1);
            switch ($sort){
                case 1:  $price->orderBy("tax_price","ASC");
                    break;
                case 2:  $price->orderBy("tax_price","DESC");
                    break;
                case 3:  $price->orderBy("no_tax_price","ASC");
                    break;
                case 4:  $price->orderBy("no_tax_price","DESC");
                    break;
                default : //默认含税升序
                    $price->orderBy("tax_price","ASC");
            }
            if ($purchase_status != "")  $price->where("ms.purchase_status",$purchase_status);
            if ($regular_pay != "") $price->where("regular_pay",$regular_pay);
            
            $price = $price->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["list"=>$price]);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:    2018-03-11
     * @Description: 商品详情-比价报价  相当于把商品搜索  和 比价结合
     */
    public function compareMoney(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            //根据1,2,3级分类。查找三级分类. 验证是否有三级分类，没有第三级分类，直接返回空
            $level_3 = Input::get('level_3'); 
            $level_2 = Input::get('level_2');
            $level_1 = Input::get('level_1');
            if ($level_3 != "" || $level_2 != "" || $level_1 != "") {
                $level_arr = [0]; //如果结果是空的，whereIN 中不能是空的
                $level = SupplyClassification::select("supply_classification.*")
                        ->leftJoin("supply_classification as lev2","supply_classification.parent_id","=","lev2.id")
                        ->leftJoin("supply_classification as lev1", "lev2.parent_id","=","lev1.id");
                if($level_3 != "") {
                    $level->where("supply_classification.level",3);
                    $level->where("supply_classification.id",$level_3);
                }
                if($level_2 != "") {
                    $level->where("lev2.level",2);
                    $level->where("lev2.id",$level_2);
                }
                if($level_1 != "") {
                    $level->where("lev1.level",1);
                    $level->where("lev1.id",$level_1);
                }
                $level = $level->orderBy("supply_classification.id")->get();
                if (!empty($level)) {
                    foreach ($level as $v) {
                        $level_arr[] =  $v->id;
                    }
                }
            }
            
            //验证车型是否有对应的耗材,车型没有对应的耗材，直接返回空
            $model_id = Input::get('model_id');
            if ($model_id != "") {
                $dpi_arr = [0];
                $dpi = DataSupplyProductItem::select("supply_item_id")->where("status",1)->where("car_model_id",$model_id)->groupBy("supply_item_id")->get();
                if (!empty($dpi)) {
                    foreach ($dpi as $v) {
                        $dpi_arr[] = $v['supply_item_id'];
                    }
                }

            }

            //开始耗材查询
            $status = Input::get('status');
            $type = Input::get('type');
            $volume_size = Input::get('volume_size'); //计量数量
            $unit_id = Input::get('unit_id');//计量单位id
            $brand_name = Input::get('brand_name');//耗材品牌
            $series_name = Input::get('series_name');//耗材系列
            $code = Input::get('code');//耗材编码
            $sale_unit_id = Input::get('sale_unit_id');//商品单位id
            $retrieval_code = Input::get('retrieval_code');//商品信息
            $supplier_name = Input::get('supplier_name');//供应商名称
            $purchase_status  = Input::get('purchase_status');//供应商状态 0 关闭 1正常
            $regular_pay = Input::get('regular_pay');//是否定期结算 1是 0否（现金结算）
            $sort = Input::get('sort'); //报价排序  1含升,  2含降,  3无升,  4 无降
            
            $search_arr = ["si.id as si_id","si.brand_id","si.brand_name","si.model","si.status","si.type","si.name","supplier_goods_price.id","supplier_goods_price.tax_price","supplier_goods_price.no_tax_price","ms.id as suppler_id","ms.status as suppler_status","ms.purchase_status","ms.name as suppler_name","ms.regular_pay"];
            $list = SupplierGoodsPrice::leftJoin("supply_item as si","supplier_goods_price.goods_id","=","si.id")
                    ->leftJoin("maintenance_supplier as ms","supplier_goods_price.supplier_id","=","ms.id")
                    ->select($search_arr)
                    ->where("supplier_goods_price.status",1);
            if ($retrieval_code != "") $list->where("si.retrieval_code","like",'%'.$retrieval_code.'%');
            if ($status != "") $list->where("si.status",$status);
            if ($type != "") $list->where("si.type",$type);
            if ($volume_size != "") $list->where("si.volume_size","like",'%'.$volume_size.'%');
            if ($unit_id != "") $list->where("si.unit_id",$unit_id);
            if ($brand_name != "") $list->where("si.retrieval_code","like",'%'.$brand_name.'%');
            if ($series_name != "") $list->where("si.retrieval_code","like",'%'.$series_name.'%');
            if ($code != "") $list->where("si.retrieval_code","like",'%'.$code.'%');
            if ($sale_unit_id != "") $list->where("si.sale_unit_id",$sale_unit_id);
            if ($model_id != "") $list->whereIn("si.id",$dpi_arr); //如果有此条件，$dpi_arr就会被赋值，赋值后是空的，就搜不到了
            if ($level_3 != "" || $level_2 != "" || $level_1 != "") $list->whereIn("supply_classification_id",$level_arr); //如果有此条件，并且前面的判断没有中断，说明$level_arr有值

            if ($supplier_name != "") $list->where("ms.name","like",'%'.$supplier_name.'%');//供应商名称
            if ($purchase_status != "")  $list->where("ms.purchase_status",$purchase_status);
            if ($regular_pay != "") $list->where("regular_pay",$regular_pay);
            
            $list->orderBy("si.id","ASC");
            switch ($sort){
                case 1:  $list->orderBy("tax_price","ASC");
                    break;
                case 2:  $list->orderBy("tax_price","DESC");
                    break;
                case 3:  $list->orderBy("no_tax_price","ASC");
                    break;
                case 4:  $list->orderBy("no_tax_price","DESC");
                    break;
                default : //默认含税升序
                    $list->orderBy("tax_price","ASC");
            }
            
            $count = $list->count();
            $page_size = Input::get("page_size",20);
            $page = Input::get("page",1);
            $list = $list->skip($page_size*($page-1))->take($page_size)->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ['count'=>$count,"list"=>$list]);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/search", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-4-20 上午10:36
     * @Description: 采购询价
     * @param string $token             用户token
     * @param string $name              商品信息
     * @param int $level_1              一级分类
     * @param int $level_2              二级分类
     * @param int $level_3              三级分类
     * @param int $supplier_type        供应商类型 1:直营店(门店);2:商户(经销商平台、康众平台);
     * @param int $type                 耗材类型 [1:非标准耗材;0:标准耗材;]
     * @param int $status               耗材状态 [1:正常;0:关闭;]
     * @param string $volume_size       计量数量 
     * @param int $unit_id              计量单位id
     * @param string $brand_name        耗材品牌信息
     * @param string $series_name       耗材系列信息
     * @param string $code              耗材商品编码
     * @param int $sale_unit_id         商品单位id
     * @param string $supplier_name     供应商名称
     * @param int $surplus_type         是否有货(是否有库存)  1:有;2:无;
     * @param int $regular_pay          是否定期结算 [0:否;1:是; 现金结算]
     * @param int $sort                 报价排序 [1含税升, 2含税降]
     * @param int $model_id             车辆车型id
     * @param int $purchase_status      供应商状态 0 关闭 1正常 （默认为1正常）
     * @link http://api.anhui.com/v1/pms/product/query_price_new?token=d416f52ad7558e0b6292447a6c5ac694
     */
    public function query_price_new(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("pms_error.args_error_100000");
                break;
            }
            $res = $this->verificationPMSUserToken(Input::get("token"),$response);
            if ($res['status'] == 0) {
                $response = $res['response'];
                break;
            }
            
            $num = Input::get('num', 1000);    //查询出耗材id的数量
            
            $name = Input::get('name');     //商品信息
            //retrieval_code    耗材的检索码
            $level_1 = Input::get('level_1');           //一级分类
            $level_2 = Input::get('level_2');           //二级分类
            $level_3 = Input::get('level_3');           //三级分类
            $supplier_type = Input::get('supplier_type');   //供应商类型 1:直营店(门店);2:商户(经销商平台、康众平台);
            $type = Input::get('type');                 //耗材类型  [1:非标;0:标准;]
            $status = Input::get('status');             //耗材状态  [1:正常;0:关闭;]
            $volume_size = Input::get('volume_size');   //计量数量
            $unit_id = Input::get('unit_id');           //计量单位
            $brand_name = Input::get('brand_name');     //品牌信息
            $series_name = Input::get('series_name');   //系列信息
            $code = Input::get('code');                 //商品编码
            $sale_unit_id = Input::get('sale_unit_id'); //商品单位
            $supplier_name = trim(Input::get('supplier_name'));  //供应商名称
            $surplus_type = Input::get('surplus_type');  //是否有货(是否有库存)  1:有;2:无;
            $regular_pay = Input::get('regular_pay');    //是否定期结算 1是 0否（现金结算）
            $sort = Input::get('sort');                  //报价排序 1含税升,  2含税降
            $model_id = Input::get('model_id');          //车辆车型
            $purchase_status = Input::get('purchase_status');//供应商状态 0 关闭 1正常 （默认为1正常）
            
            //根据1,2,3级分类 查找三级分类. 验证是否有三级分类，没有第三级分类，直接返回空
            $level_arr = [];    //耗材三级分类id数组
            if($level_1 != '' || $level_2 != '' || $level_3 != ''){
                $level = SupplyClassification::select('supply_classification.id', 'supply_classification.name')
                        ->leftJoin('supply_classification AS lev2', 'supply_classification.parent_id', '=', 'lev2.id')
                        ->leftJoin('supply_classification AS lev1', 'lev2.parent_id', '=', 'lev1.id');
                if($level_3 != ''){
                    $level->where('supply_classification.level', 3);
                    $level->where('supply_classification.id', $level_3);
                }
                if($level_2 != ''){
                    $level->where('lev2.level', 2);
                    $level->where('lev2.id', $level_2);
                }
                if($level_1 != ''){
                    $level->where('lev1.level', 1);
                    $level->where('lev1.id', $level_1);
                }
                $level = $level->orderBy('supply_classification.id')->get();
                if(!empty($level)){
                    foreach ($level as $v) {
                        $level_arr[] = $v->id;
                    }
                }
            }
            //      获取有效的 耗材id、耗材erp_id  start
            $supply_item_id = [];       //耗材id数组
            $supply_item_erp_id = [];   //耗材erp_id数组
            $supply_item_info = [];     //查询出来的耗材详细信息    erp id 作为key
            //根据车型 查询出所对应耗材的 耗材id、耗材erp_id
            if ($model_id != '') {
                $select_str = 'anhui.supply_item.id, anhui.supply_item.brand_id, anhui.supply_item.brand_name, '
                        . 'anhui.supply_item.model, anhui.supply_item.status, anhui.supply_item.type, '
                        . 'anhui.supply_item.name, anhui.supply_item.erp_id';
                $spi_arr = DB::table('anhui_data.supply_product_item')
                        ->leftJoin('anhui.supply_item', 'supply_product_item.supply_item_id', '=', 'anhui.supply_item.erp_id')
                        ->select(DB::raw($select_str))
                        ->where('anhui_data.supply_product_item.status', 1)
                        ->where('anhui_data.supply_product_item.car_model_id', $model_id)
                        ->groupBy('anhui_data.supply_product_item.supply_item_id')
                        ->skip(0)->take($num)->get();
            } else {
                $spi_arr = [];
            }
            if(!empty($spi_arr)){
                foreach ($spi_arr as $v) {
                    $supply_item_id[] = $v->id;
                    $supply_item_erp_id[] = $v->erp_id;
                    $supply_item_info[$v->erp_id]['id'] = $v->id;
                    $supply_item_info[$v->erp_id]['brand_id'] = $v->brand_id;
                    $supply_item_info[$v->erp_id]['brand_name'] = $v->brand_name;
                    $supply_item_info[$v->erp_id]['model'] = $v->model;
                    $supply_item_info[$v->erp_id]['status'] = $v->status;
                    $supply_item_info[$v->erp_id]['type'] = $v->type;
                    $supply_item_info[$v->erp_id]['name'] = $v->name;
                }
            }
            
            //根据搜索条件查询出符合条件的 耗材id、耗材erp_id
            $item_list = DB::table('supply_item')->select('id', 'brand_id', 'brand_name', 'model', 'status', 'type', 'name', 'retrieval_code', 'erp_id');
            if($name != ''){  //商品信息
                $item_list->where('retrieval_code', 'like', '%'.$name.'%');
            }
            if(!empty($level_arr)){ //三级分类
                $item_list->whereIn('supply_classification_id', $level_arr);  //基础分类
            }
            if($type != ''){   //耗材类型
                $item_list->where('type',$type);
            }
            if($status != ''){   //耗材状态
                $item_list->where('status',$status);
            }
            if($volume_size != ''){ //计量数量
                $item_list->where('volume_size', 'like', '%'.$volume_size.'%');
            }
            if($unit_id != ''){ //计量单位
                $item_list->where('unit_id', $unit_id);
            }
            if($brand_name != ''){ //品牌信息
                $item_list->where('retrieval_code', 'like', '%'.$brand_name.'%');
            }
            if($series_name != ''){ //系列信息
                $item_list->where('retrieval_code', 'like', '%'.$series_name.'%');
            }
            if($code != ''){ //商品编码
                $item_list->where('retrieval_code', 'like', '%'.$code.'%');
            }
            if($sale_unit_id != ''){    //商品单位
                $item_list->where('sale_unit_id', $sale_unit_id);
            }
            $item_list = $item_list->skip(0)->take($num)->get();
            
            if(!empty($item_list)){
                foreach ($item_list as $v) {
                    $supply_item_id[] = $v->id;
                    $supply_item_erp_id[] = $v->erp_id;
                    $supply_item_info[$v->erp_id]['id'] = $v->id;
                    $supply_item_info[$v->erp_id]['brand_id'] = $v->brand_id;
                    $supply_item_info[$v->erp_id]['brand_name'] = $v->brand_name;
                    $supply_item_info[$v->erp_id]['model'] = $v->model;
                    $supply_item_info[$v->erp_id]['status'] = $v->status;
                    $supply_item_info[$v->erp_id]['type'] = $v->type;
                    $supply_item_info[$v->erp_id]['name'] = $v->name;
                }
            }
            //      获取有效的 耗材id、耗材erp_id  end

            //查询出的门店报价数据
            //supplier_type 供应商类型 1:门店;2:商户 经销商平台、康众平台;
            $sc_list = [];      //门店报价数据数组
            if($supplier_type != 2 && !empty($supply_item_id)){     //耗材id数组不能为空
                $sc_str = 'MAX(maintenance_storage_item.tax_purchase_price) AS tax_purchase_price, '
                        . 'MAX(maintenance_storage_item.no_tax_purchase_price) AS no_tax_purchase_price, '
                        . 'SUM(current_number) AS current_number, supply_item.id AS si_id, supply_item.brand_id, '
                        . 'supply_item.brand_name, supply_item.model, supply_item. status,supply_item.type, supply_item.name, '
                        . 'maintenance_shops.name AS shop_name, 1 AS regular_pay, 1 AS supplier_type';
                $sc_list = MaintenanceStorageItem::leftJoin('maintenance_shops', 'maintenance_storage_item.shop_id', '=', 'maintenance_shops.id')
                        ->leftJoin('supply_item', 'maintenance_storage_item.item_id', '=', 'supply_item.id')
                        ->select(DB::raw($sc_str))
                        ->groupBy('maintenance_storage_item.shop_id')->groupBy('maintenance_storage_item.item_id')
                        ->where('maintenance_storage_item.type', '1')
                        ->where('maintenance_storage_item.status', '1')
                        ->where('maintenance_shops.status', '1');
                if(!empty($supply_item_id)){    //匹配 耗材id
                    $sc_list->whereIn('maintenance_storage_item.item_id', $supply_item_id);
                }
                if($supplier_name != ''){ //搜索门店名称
                    $sc_list->where('maintenance_shops.name', 'like', '%'.$supplier_name.'%');
                }
                if($surplus_type == 1){ //门店或者供应商有货
                    $sc_list->where('current_number', '>', '0');
                }elseif ($surplus_type == 2) {  //门店或者供应商无货
                    $sc_list->where('current_number', '<=', '0');
                }
                //$sc_list = $sc_list->skip(0)->take($num)->get()->toArray();      //查询出的门店报价数据
                $sc_list = $sc_list->skip(0)->take(500)->get()->toArray();      //查询出的门店报价数据
            }
            
            $gongyingshang_res = [];    //经销商平台 、康众 平台的应返回的数据
            if($supplier_type != 1){    //查询经销商平台 、康众 平台的报价数据
                //查询出符合条件的供应商id
                $supplier_erp_id = [];  //供货商所对应的erp_id
                $supplier_info = [];     //查询出来的耗材详细信息   erp id 作为key
                $supplier_list = MaintenanceSupplier::select('id', 'erp_id', 'name', 'regular_pay');
                if(!empty($supplier_name)){ //供应商名称
                    $supplier_list->where('name', 'like', '%'.$supplier_name.'%');
                }
                if($regular_pay != ''){   //是否定期结算 1是 0否（现金结算）
                    $supplier_list->where('regular_pay', $regular_pay);
                }
                if($purchase_status != ''){   //供应商状态 0 关闭 1正常 （默认为1正常）
                    $supplier_list->where('purchase_status', $purchase_status);
                }              
                //$supplier_list = $supplier_list->skip(0)->take($num)->get()->toArray();
                $supplier_list = $supplier_list->skip(0)->take($num)->get();
                
                if(!empty($supplier_list)){
                    foreach ($supplier_list as $v) {
//                        $supplier_erp_id[] = $v['erp_id'];
//                        $supplier_info[$v['erp_id']]['id'] = $v['id'];
//                        $supplier_info[$v['erp_id']]['name'] = $v['name'];
//                        $supplier_info[$v['erp_id']]['regular_pay'] = $v['regular_pay'];
                        
                        $supplier_erp_id[] = $v->erp_id;
                        $supplier_info[$v['erp_id']]['id'] = $v->id;
                        $supplier_info[$v['erp_id']]['name'] = $v->name;
                        $supplier_info[$v['erp_id']]['regular_pay'] = $v->regular_pay;
                    }
                    
                }
                
                //获取本身的门店id  PMS 平台的门店id 为 '亚运村总店的门店id' 固定为 1
                $shop_id = 1;
                
                //通过 经销商平台 、康众平台获取数据
                $gongyingshang_info = GYSQueryPrice::getQueryPriceList($supply_item_erp_id, $supplier_erp_id, $shop_id);
                if(!empty($gongyingshang_info)){
                    foreach ($gongyingshang_info as $k => $v) {
                        if ($surplus_type == 2) {  //门店或者供应商无货
                            if($v['storage'] > 0 || $v['storage'] == -1){
                                unset($gongyingshang_info[$k]);
                                continue;
                            }
                        }
                        if ($type == 1) {  //耗材类型  [1:非标;0:标准;]
                            unset($gongyingshang_info[$k]);
                            continue;
                        }
                        
                        $gongyingshang_res[$k]['tax_purchase_price'] = $v['price'];
                        $gongyingshang_res[$k]['no_tax_purchase_price'] = $v['price'];
                        $gongyingshang_res[$k]['current_number'] = $v['storage'];
                        if(isset($supply_item_info[$v['item_id']])){
                            $gongyingshang_res[$k]['si_id'] = $supply_item_info[$v['item_id']]['id'];   //erp id转换成 耗材id
                            $gongyingshang_res[$k]['brand_id'] = $supply_item_info[$v['item_id']]['brand_id'];
                            $gongyingshang_res[$k]['brand_name'] = $supply_item_info[$v['item_id']]['brand_name'];
                            $gongyingshang_res[$k]['model'] = $supply_item_info[$v['item_id']]['model'];
                            $gongyingshang_res[$k]['status'] = $supply_item_info[$v['item_id']]['status'];
                            $gongyingshang_res[$k]['type'] = $supply_item_info[$v['item_id']]['type'];
                            $gongyingshang_res[$k]['name'] = $supply_item_info[$v['item_id']]['name'];    
                        }else{
                            $item_id_info = SupplyItem::where('erp_id', $v['item_id'])->first()->toArray(); //查询具体耗材的信息
                            $gongyingshang_res[$k]['si_id'] = $item_id_info['id'];   //erp id转换成 耗材id
                            $gongyingshang_res[$k]['brand_id'] = $item_id_info['brand_id'];
                            $gongyingshang_res[$k]['brand_name'] = $item_id_info['brand_name'];
                            $gongyingshang_res[$k]['model'] = $item_id_info['model'];
                            $gongyingshang_res[$k]['status'] = $item_id_info['status'];
                            $gongyingshang_res[$k]['type'] = $item_id_info['type'];
                            $gongyingshang_res[$k]['name'] = $item_id_info['name'];
                        }
                        
                        if(isset($supplier_info[$v['suppller_id']])){
                            $gongyingshang_res[$k]['suppller_id'] = $supplier_info[$v['suppller_id']]['id'];    //供应商id  cms的供应商id
                            $gongyingshang_res[$k]['shop_name'] = $supplier_info[$v['suppller_id']]['name'];    //供应商的名称
                            $gongyingshang_res[$k]['regular_pay'] = $supplier_info[$v['suppller_id']]['regular_pay'];//是否定期结算
                        }else{
                            $supplier_id_info = MaintenanceSupplier::where('erp_id', $v['suppller_id'])->first()->toArray(); //查询具体供应商的信息
                            $gongyingshang_res[$k]['suppller_id'] = $supplier_info[$v['suppller_id']]['id'];    //供应商id  cms的供应商id
                            $gongyingshang_res[$k]['shop_name'] = $supplier_id_info['name'];    //供应商的名称
                            $gongyingshang_res[$k]['regular_pay'] = $supplier_id_info['regular_pay'];//是否定期结算
                        }
                        
                        $gongyingshang_res[$k]['supplier_type'] = 2;    //供应商的类型
                    }
                }
            }
            if($regular_pay != '' && $regular_pay == 0){   //是否定期结算 1是 0否（现金结算）
                //由于门店的定期结算都为1 开启， 所以搜索定期结算关闭的时候，门店的相关数据为空
                $all_list = $gongyingshang_res;
            }else{
                $all_list = array_merge($sc_list, $gongyingshang_res);
            }
            
            //排序处理  start      耗材id顺序（正序）排序 -> 含税升序/含税降序
            $sort_id = [];      //待排序的耗材id
            $sort_price = [];   //待排序的含税报价
            foreach ($all_list as $k => $v) {
                $sort_id[] = $v['si_id'];
                $sort_price[] = $v['tax_purchase_price'];
//                $all_list[$k]['tax_purchase_price'] = Common::upFow($v['tax_purchase_price']);      //价格末尾去除0
//                $all_list[$k]['no_tax_purchase_price'] = Common::upFow($v['no_tax_purchase_price']);
            }               
            switch ($sort) {    //报价排序 1含税升,  2含税降
                case 1:
                    array_multisort($sort_id, $sort_price, $all_list);
                    break;
                case 2:
                    array_multisort($sort_id, $sort_price, SORT_DESC, $all_list);
                    break;
                default:
                    array_multisort($sort_id, $all_list);
                    break;
            }
            //排序处理  end
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $all_list);
        } while (false);
         Log::info("info", array("system" => "pms" ,"event" => "product/query_price_new", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}